package jpb.security;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import io.jsonwebtoken.*;
import jpb.constant.StatusCode;
import jpb.module.daomain.manager.Manager;
import jpb.module.daomain.member.Member;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * Created by haol on 2017/3/16.
 */

public class HandleToken {


        @Value("${spring.profiles.active}")
        private String profiles;

        Logger logger = LoggerFactory.getLogger(HandleToken.class);



        public SecretKey generalKey() {
                String stringKey = profiles + StatusCode.JWT_SECRET;
                byte[] encodedKey = Base64.decodeBase64(stringKey);
                SecretKey key = new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
                return key;
        }

        /**
         * 存储当前登录用户的信息到jwt
         *
         * @param manager
         * @return
         */
        public String generalSubject(Manager manager) {
                Gson gson = new Gson();
                manager.setPassword(null);
                return gson.toJson(manager);
        }
        public String generalSubject(Member member) {
                Gson gson = new Gson();
                return gson.toJson(member);
        }
        public Claims parseJWT(String jwt) {
                try {
                        SecretKey key = generalKey();
                        Claims claims = Jwts.parser().setSigningKey(key).parseClaimsJws(jwt).getBody();
                        return claims;
                } catch (ExpiredJwtException ee) {
                        logger.error(ee.getMessage());
                        logger.error("用户签名信息超过有效期，需重新登录");
                        return null;
                } catch (SignatureException se) {
                        logger.error(se.getMessage());
                        logger.error("用户签名信息非法，需重新登录");
                        return null;
                } catch (Exception e) {
                        logger.error(e.getMessage());
                        logger.error("未知错误，需重新登录");
                        return null;
                }
        }

        /**
         * 获取当前登录用户的个人信息
         *
         * @param token
         * @return
         * @throws Exception
         */
        public String getValueByKey(String token, String key) {
                Claims claims = this.parseJWT(token);
                JSONObject jsonArray = JSONObject.parseObject(claims.getSubject());
                String ths = jsonArray.getString(key);
                return ths;

        }

        public String getSubject(String token) {
                Claims claims = this.parseJWT(token);
                return claims.getSubject();
        }
        public Date getIssuedAt(String token) {
                Claims claims = this.parseJWT(token);
                return claims.getIssuedAt();
        }


        public <T> T getObject(String token, Class<T> type) {
                Claims claims = this.parseJWT(token);
                Gson gson = new Gson();
                T obj = gson.fromJson(claims.getSubject(), type);
                return obj;

        }

        public boolean analyzeJWT(String jwt) {
                if (this.parseJWT(jwt) == null) {
                        return false;
                } else {
                        return true;
                }

        }

        public String getTokenOid(HttpServletRequest request){
                String  token = HandleCookie.getValueByName(request, StatusCode.COOKIE_JWT_WEB);
                return this.getValueByKey(token,"id");
        }
}

